<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>物料图片采集</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .container {
            padding: 15px 15px 100px;
            max-width: 600px;
            margin: 0 auto;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .input-group {
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            /* flex-shrink: 0; */
            border-radius: 8px;
            display: flex;
            background: #fff;
            /* flex-direction: row; */
        }

        .input-label {
            width: 35%;
            margin-top: 10px;
            display: block;
            margin-bottom: 8px;
            font-size: 16px;
            color: #333;
            padding: 7px;
            margin-right: -31px;
        }

        label.input-label {
        }

        .input-field {
            width: 100%;
            margin-left: 10px;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            background-color: #fff;
            cursor: pointer;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            /*z-index: 1000;*/
        }

        .modal-content {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 20px;
            border-radius: 12px;
            width: 90%;
            height: 65%;
            max-width: 500px;
        }

        .search-container {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            margin-top: 20px;
        }

        .search-input {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }

        .search-btn {
            padding: 12px 24px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
        }

        .search-btn:active {
            background-color: #0056b3;
        }

        /* 搜索结果列表样式 */
        .result-list {
            background-color: #fff;
            border-radius: 8px;
            overflow: hidden;
            max-height: 320px; /* 添加最大高度 */
            overflow-y: auto; /* 允许垂直滚动 */
        }

        .result-item {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            display: grid;
            grid-template-columns: 100px 1fr; /* 分成两列，第一列固定宽度 */
            gap: 15px;
            align-items: start; /* 顶部对齐，允许第二列换行 */
        }

        .item-code {
            color: #666;
            font-size: 14px;
            font-family: monospace; /* 等宽字体，更适合显示代码 */
        }

        .item-name {
            font-size: 15px;
            line-height: 1.4;
            word-break: break-all; /* 允许在任何字符间换行 */
        }

        .result-item:hover {
            background-color: #f5f9ff;
        }

        /* 关闭按钮 */
        .close-btn {
            position: absolute;
            right: 15px;
            /* top: 15px; */
            margin-top: -33px;
            margin-right: -11px;
            font-size: 45px;
            color: #666;
            cursor: pointer;
        }

        /* 图片展示区域 */
        .image-section {
            /* margin-top: 0vh; */
            padding: 15px;
            border-radius: 8px;
            background: #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            flex-shrink: 0;
            position: relative;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }

        /* 左侧预览和右侧上传区域共同样式 */
        .preview-side,
        .upload-side {
            flex: 1;
            min-width: 0;
            width: 50%;
        }

        .image-preview {
            width: 100%;
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
            position: relative;
            padding-top: 100%;
            background-color: #f8f8f8;
        }

        .image-preview img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: contain;
            padding: 8px;
            background-color: transparent; /* 添加透明背景 */
        }

        /* 修改预览图片初始状态 */
        #previewImage[src=""],
        #previewImage[src=""] {
            opacity: 0; /* 完全透明 */
        }

        .image-container {
            display: block;
        }

        .image-box {
            position: relative;
            padding-top: 100%;
            border: 2px dashed #ddd;
            border-radius: 8px;
            overflow: hidden;
            margin: 0 auto;
            background-color: #f8f8f8;
        }

        /* 删除按钮样式 */
        .delete-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 24px;
            height: 24px;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
            display: none;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 16px;
            cursor: pointer;
            z-index: 2;
            transition: all 0.2s ease;
        }

        .delete-btn:hover {
            background-color: rgba(0, 0, 0, 0.7);
        }

        .image-box img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: contain; /* 改为contain以保持图片比例 */
            display: none;
            background-color: #fff;
        }

        /* 优化添加按钮样式 */
        .add-image-btn {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 48px;
            height: 48px;
            background-color: #007bff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 28px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .add-image-btn:hover {
            background-color: #0056b3;
            transform: translate(-50%, -50%) scale(1.05);
        }

        /* 图片操作菜单 */
        .image-menu {
            display: none;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background: #fff;
            border-radius: 16px 16px 0 0;
            padding: 20px;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }

        .menu-option {
            padding: 15px;
            text-align: center;
            font-size: 16px;
            border-bottom: 1px solid #eee;
            color: #007bff;
        }

        .menu-option:last-child {
            border-bottom: none;
        }

        /* 提交按钮容器样式 */
        .submit-btn {
            position: relative;
            width: 100%;
            height: 44px;
            /*margin-top: 47vh;*/
            background: #007bff;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            /* display: flex; */
            align-items: center;
            justify-content: center;
            /* cursor: pointer; */
        }

        .submit-btn:active {
            background: #0056b3;
        }

        /* 为预览框添加删除按钮 */
        .preview-delete-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 24px;
            height: 24px;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
            display: none;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 16px;
            cursor: pointer;
            z-index: 2;
            transition: all 0.2s ease;
        }

        .preview-delete-btn:hover {
            background-color: rgba(0, 0, 0, 0.7);
        }

    </style>
</head>
<body>
<div class="container">
    <div class="input-group">
        <label class="input-label">物料编号/名称</label>
        <input type="text" class="input-field" id="materialName" readonly placeholder="点击选择物料" onclick="openModal()">
        <input type="hidden" id="cdcmMaterialNo" readonly>

    </div>

    <!-- 修改后的图片展示区域 -->
    <div class="image-section">
        <!-- 左侧预览区域 -->
        <div class="preview-side">
            <div class="image-preview">
                <img id="previewImage" src="" alt="">
                <div class="preview-delete-btn" onclick="deletePreviewImage()">×</div>
            </div>
        </div>

        <!-- 右侧图片框区域 -->
        <div class="upload-side">
            <div class="image-container">
                <div class="image-box">
                    <img id="materialImage1" class="material-image" src="" alt="物料图片">
                    <div class="add-image-btn" onclick="showImageMenu(1)">+</div>
                </div>
            </div>
        </div>

        <!-- 提交按钮放在图片区域内部的底部 -->
        <button class="submit-btn" onclick="submitData()">提交</button>
    </div>
</div>

<!-- 模态框 -->
<div class="modal" id="searchModal">
    <div class="modal-content">
        <span class="close-btn" onclick="closeModal()">&times;</span>
        <div class="search-container">
            <input type="text" class="search-input" id="searchInput" placeholder="请输入物料编号或名称">
            <button class="search-btn" onclick="searchMaterial()">查询</button>
        </div>
        <div class="result-list" id="resultList">
            <!-- 搜索结果将动态插入这里 -->
        </div>
    </div>
</div>

<!-- 添加图片操作菜单 -->
<div class="image-menu" id="imageMenu">
    <div class="menu-option" onclick="takePhoto()">拍照</div>
    <div class="menu-option" onclick="chooseFromAlbum()">从相册选择</div>
    <div class="menu-option" onclick="closeImageMenu()">取消</div>
</div>

<!-- 添加文件选择输入框 -->
<input type="file" id="fileInput" accept="image/*" style="display: none" onchange="handleImageSelect(this)">

<script>
    // 打开模态框
    function openModal() {
        document.getElementById('searchModal').style.display = 'block';
    }

    // 关闭模态框
    function closeModal() {
        document.getElementById('searchModal').style.display = 'none';
    }

    // 使用代理服务器方式
    function searchMaterial() {
        const searchValue = document.getElementById('searchInput').value.trim();
        if (!searchValue) {
            alert('请输入搜索内容');
            return;
        }

        // 显示加载状态
        const resultList = document.getElementById('resultList');
        resultList.innerHTML = '<div style="text-align: center; padding: 20px;">正在搜索...</div>';

        // 使用相对路径，通过代理服务器转发请求
        const url = `http://172.24.222.104:9004/upload/queryMaterialImgUrl/queryMaterialImgUrl?cdcmMaterialNo=${encodeURIComponent(searchValue)}&token=0eshj9836251jhsuessdf08761ehehesf12e1`;

        // 发起API请求
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('Received data:', data);
                displayResults(data);
            })
            .catch(error => {
                console.error('搜索请求失败:', error);
                resultList.innerHTML = `
                        <div style="text-align: center; padding: 20px; color: #ff4444;">
                            搜索请求失败<br>
                            <small style="color: #666;">请检查网络连接或联系管理员</small>
                        </div>
                    `;
            });
    }

    // 显示搜索结果
    function displayResults(results) {
        const resultList = document.getElementById('resultList');
        resultList.innerHTML = '';

        if (!results || results.length === 0) {
            resultList.innerHTML = '<div class="result-item" style="text-align: center; color: #999;">未找到相关物料</div>';
            return;
        }

        results.forEach(item => {
            const div = document.createElement('div');
            div.className = 'result-item';
            div.innerHTML = `
                    <div class="item-code">${item.cdcmMaterialNo || ''}</div>
                    <div class="item-name">${item.cdcmNameCn || ''}</div>
                `;
            div.onclick = () => selectMaterial(item);
            resultList.appendChild(div);
        });
    }

    // 选择物料
    function selectMaterial(item) {
        // 直接使用传入的item数据先更新界面
        document.getElementById('materialName').value = ` ${item.cdcmNameCn}`;
        document.getElementById('cdcmMaterialNo').value = ` ${item.cdcmMaterialNo}`;

        // 更新图片
        const previewImage = document.getElementById('previewImage');
        const previewDeleteBtn = document.querySelector('.preview-delete-btn');

        if (item.cdcmImgUrl) {
            // 创建新的Image对象来预加载图片
            const img = new Image();
            img.onload = function () {
                previewImage.src = item.cdcmImgUrl;
                previewImage.style.display = 'block';
                previewDeleteBtn.style.display = 'flex';
            };
            img.onerror = function () {
                previewImage.style.display = 'none';
                previewImage.src = '';
                previewDeleteBtn.style.display = 'none';
            };
            img.src = item.cdcmImgUrl;
        } else {
            previewImage.style.display = 'none';
            previewImage.src = '';
            previewDeleteBtn.style.display = 'none';
        }

        closeModal();

        // 然后在后台重新获取最新数据
        const url = `http://172.24.222.104:9004/upload/queryMaterialImgUrl/queryMaterialImgUrl?cdcmMaterialNo=${encodeURIComponent(item.cdcmMaterialNo)}&token=0eshj9836251jhsuessdf08761ehehesf12e1`;

        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 检查返回的数据
                if (data && Array.isArray(data) && data.length > 0) {
                    const latestItem = data[0];

                    // 如果获取到新数据，更新界面
                    if (latestItem.cdcmNameCn && latestItem.cdcmMaterialNo) {
                        document.getElementById('materialName').value = ` ${latestItem.cdcmNameCn}`;
                        document.getElementById('cdcmMaterialNo').value = ` ${latestItem.cdcmMaterialNo}`;

                        if (latestItem.cdcmImgUrl) {
                            // 处理图片URL，移除:443
                            let processedImgUrl = latestItem.cdcmImgUrl;
                            if (processedImgUrl.includes(':443')) {
                                processedImgUrl = processedImgUrl.replace(':443', '');
                            }

                            const newImg = new Image();
                            newImg.onload = function () {
                                previewImage.src = processedImgUrl;
                                previewImage.style.display = 'block';
                                previewDeleteBtn.style.display = 'flex';
                            };
                            newImg.onerror = function () {
                                // 如果新图片加载失败，保持原有图片
                                console.warn('新图片加载失败，保持原有图片');
                            };
                            newImg.src = processedImgUrl;
                        }
                    }
                }
            })
            .catch(error => {
                console.warn('获取最新物料数据失败:', error);
                // 不显示错误提示，因为已经使用了传入的item数据
            });
    }

    // 防止点击模态框内容时关闭模态框
    document.querySelector('.modal-content').addEventListener('click', function (e) {
        e.stopPropagation();
    });

    // 点击模态框外部关闭模态框
    document.querySelector('.modal').addEventListener('click', function (e) {
        if (e.target === this) {
            closeModal();
        }
    });

    let currentImageBox = 1;

    // 显示图片操作菜单
    function showImageMenu(imageNumber) {
        currentImageBox = imageNumber;
        document.getElementById('imageMenu').style.display = 'block';
    }

    // 关闭图片操作菜单
    function closeImageMenu() {
        document.getElementById('imageMenu').style.display = 'none';
    }

    // 删除预览图片
    function deletePreviewImage() {
        const previewImage = document.getElementById('previewImage');
        const previewDeleteBtn = document.querySelector('.preview-delete-btn');
        const fileInput = document.getElementById('fileInput');

        // 重置图片状态
        previewImage.style.display = 'none';
        previewImage.src = '';
        previewImage.removeAttribute('src');  // 完全移除src属性
        previewDeleteBtn.style.display = 'none';

        // 重置文件输入框
        fileInput.value = '';
    }

    // 从相册选择
    function chooseFromAlbum() {
        const fileInput = document.getElementById('fileInput');
        fileInput.value = ''; // 重置文件输入框的值
        fileInput.removeAttribute('capture');
        fileInput.click();
        closeImageMenu();
    }

    // 拍照
    function takePhoto() {
        // 检查是否支持调用相机
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            alert('您的浏览器不支持调用相机');
            return;
        }

        // 调用相机
        navigator.mediaDevices.getUserMedia({video: true})
            .then(function (stream) {
                const fileInput = document.getElementById('fileInput');
                fileInput.value = ''; // 重置文件输入框的值
                fileInput.setAttribute('capture', 'camera');
                fileInput.click();
            })
            .catch(function (error) {
                alert('调用相机失败：' + error);
            });

        closeImageMenu();
    }

    // 处理图片选择
    function handleImageSelect(input) {
        debugger
        if (input.files && input.files[0]) {
            const reader = new FileReader();

            reader.onload = function (e) {
                const previewImage = document.getElementById('previewImage');
                const previewDeleteBtn = document.querySelector('.preview-delete-btn');

                // 创建新的Image对象来预加载图片
                const img = new Image();
                img.onload = function () {
                    previewImage.src = e.target.result;
                    previewImage.style.display = 'block';
                    previewDeleteBtn.style.display = 'flex';
                };
                img.src = e.target.result;
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

    // 提交数据
    function submitData() {
        const submitBtn = document.querySelector('.submit-btn');
        const cdcmMaterialNo = document.getElementById('cdcmMaterialNo').value;
        const previewImage = document.getElementById('previewImage');

        if (!cdcmMaterialNo) {
            alert('请选择物料');
            return;
        }

        // 检查预览图片是否存在
        if (!previewImage.src || previewImage.style.display === 'none') {
            alert('请添加一张物料图片');
            return;
        }

        // 检查是否是服务器图片且没有更新
        const materialName = document.getElementById('materialName').value;
        if (!previewImage.src.startsWith('data:') && materialName.trim()) {
            alert('图片没有更新');
            return;
        }

        // 禁用提交按钮防止重复提交
        submitBtn.disabled = true;
        submitBtn.style.backgroundColor = '#0056b3';

        // 创建FormData对象
        const formData = new FormData();
        formData.append('skuCode', cdcmMaterialNo.trim());
        formData.append('token', '0eshj9836251jhsuessdf08761ehehesf12e1');

        // 判断图片来源
        if (previewImage.src.startsWith('data:')) {
            // 如果是本地上传的图片（base64格式）
            fetch(previewImage.src)
                .then(res => res.blob())
                .then(blob => {
                    formData.append('file', blob, 'image.jpg');
                    uploadToServer(formData, submitBtn);
                })
                .catch(error => {
                    submitBtn.disabled = false;
                    submitBtn.style.backgroundColor = '#007bff';
                    alert('图片处理失败：' + error.message);
                });
        } else {
            // 如果是服务器图片URL，直接使用URL进行上传
            fetch(previewImage.src)
                .then(response => response.blob())
                .then(blob => {
                    formData.append('file', blob, 'image.jpg');
                    uploadToServer(formData, submitBtn);
                })
                .catch(error => {
                    submitBtn.disabled = false;
                    submitBtn.style.backgroundColor = '#007bff';
                    alert('图片处理失败，请重新上传图片');
                });
        }
    }

    // 上传到服务器的函数
    function uploadToServer(formData, submitBtn) {
        fetch('http://172.24.222.104:9004/upload/queryMaterialImgUrl/uploadSkuImg', {
            method: 'POST',
            headers: {
                'token': '0eshj9836251jhsuessdf08761ehehesf12e1'
            },
            body: formData
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                submitBtn.disabled = false;
                submitBtn.style.backgroundColor = '#007bff';
                if (data.success) {
                    alert('提交成功！');
                    // 清空表单
                    deletePreviewImage();
                    document.getElementById('materialName').value = '';
                    document.getElementById('cdcmMaterialNo').value = '';
                } else {
                    throw new Error(data.message || '未知错误');
                }
            })
            .catch(error => {
                submitBtn.disabled = false;
                submitBtn.style.backgroundColor = '#007bff';
                alert('提交失败：' + error.message);
            });
    }

    // 点击图片菜单外部关闭菜单
    document.addEventListener('click', function (e) {
        const imageMenu = document.getElementById('imageMenu');
        if (imageMenu.style.display === 'block' && !imageMenu.contains(e.target) && !e.target.classList.contains('add-image-btn')) {
            closeImageMenu();
        }
    });

</script>
</body>
</html>